from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
from web import models
from django.conf import settings
from django.urls import resolve
from datetime import datetime


class AuthMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if response.status_code == 404:
            return redirect('/web/index/')
        return response
    def process_request(self, request):
        """如果用户已经登录，则request中赋值"""
        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.user_obj = user_obj
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            if user_obj:
                return redirect('/web/index/')
            return
        if not user_obj:
            return redirect('/web/login/')

    # def process_view(self, request, view, args, kwargs):
    #     """会在process_request执行完毕后执行"""
    #     # 判断URL是否是以manage开头，如果是则判断项目ID是否是我创建 or 参与
    #     if not request.path_info.startswith('/web/manage/'):
    #         return
    #
    #     project_id = kwargs.get('project_id')
    #     # 是否是我创建的
    #     project_object = models.Project.objects.filter(creator=request.user_obj, id=project_id).first()
    #     if project_object:
    #         # 是我创建的项目的话，我就让他通过
    #         request.project = project_object
    #         return
    #
    #     # 是否是我参与的项目
    #     project_user_object = models.ProjectUser.objects.filter(user=request.user_info, project_id=project_id).first()
    #     if project_user_object:
    #         # 是我参与的项目
    #         request.project = project_user_object.project
    #         return
    #
    #     return redirect('project_list')
